package com.zhentao.datacontrol.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhentao.datacontrol.domain.entity.RuleGroup;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface RuleGroupMapper extends BaseMapper<RuleGroup> {

    /**
     * 查询树形结构的分组列表
     */
    @Select("SELECT g.*, p.group_name as parent_name " +
            "FROM dc_rule_group g " +
            "LEFT JOIN dc_rule_group p ON g.parent_id = p.id " +
            "WHERE g.is_delete = 0 " +
            "ORDER BY g.group_level, g.sort_order, g.id")
    List<RuleGroup> selectTreeList();

    /**
     * 查询指定父级下的子分组
     */
    @Select("SELECT * FROM dc_rule_group " +
            "WHERE parent_id = #{parentId} AND is_delete = 0 " +
            "ORDER BY sort_order, id")
    List<RuleGroup> selectByParentId(@Param("parentId") Long parentId);

    /**
     * 查询顶级分组
     */
    @Select("SELECT * FROM dc_rule_group " +
            "WHERE parent_id IS NULL AND is_delete = 0 " +
            "ORDER BY sort_order, id")
    List<RuleGroup> selectTopLevel();

    /**
     * 检查分组名称是否存在
     */
    @Select("SELECT COUNT(*) FROM dc_rule_group " +
            "WHERE group_name = #{groupName} " +
            "AND (parent_id = #{parentId} OR (parent_id IS NULL AND #{parentId} IS NULL)) " +
            "AND is_delete = 0 " +
            "AND (#{id} IS NULL OR id != #{id})")
    int checkGroupNameExists(@Param("groupName") String groupName,
                           @Param("parentId") Long parentId,
                           @Param("id") Long id);

    /**
     * 获取下一个排序号
     */
    @Select("SELECT COALESCE(MAX(sort_order), 0) + 1 FROM dc_rule_group " +
            "WHERE (parent_id = #{parentId} OR (parent_id IS NULL AND #{parentId} IS NULL)) AND is_delete = 0")
    Integer getNextSortOrder(@Param("parentId") Long parentId);

    /**
     * 更新排序号
     */
    @Update("UPDATE dc_rule_group SET sort_order = #{sortOrder} WHERE id = #{id}")
    int updateSortOrder(@Param("id") Long id, @Param("sortOrder") Integer sortOrder);
}
